package com.shinowit.web.common;

import java.beans.PropertyEditorSupport;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RestController;

@ControllerAdvice(annotations = {Controller.class, RestController.class})
public class CommonController {

	 @InitBinder
	    public void initBinder(WebDataBinder binder) {
	        binder.registerCustomEditor(java.sql.Date.class, new PropertyEditorSupport() {

	            final SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");

	            @Override
	            public void setAsText(String text) throws IllegalArgumentException {
	            	if ((null==text) || (text.trim().length()==0)){
	            		setValue(null);
	            		return;
	            	}
	                try {
	                    java.util.Date date = sf.parse(text);
	                    setValue(new Date(date.getTime()));
	                } catch (ParseException e) {
	                    throw new IllegalArgumentException(e);
	                }
	            }
	        });
	        
	        binder.registerCustomEditor(java.util.Date.class, new PropertyEditorSupport() {

	            final SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");

	            @Override
	            public void setAsText(String text) throws IllegalArgumentException {
	            	if ((null==text) || (text.trim().length()==0)){
	            		setValue(null);
	            		return;
	            	}
	                try {
	                    java.util.Date date = sf.parse(text);
	                    setValue(date);
	                } catch (ParseException e) {
	                    throw new IllegalArgumentException(e);
	                }
	            }
	        });

	        binder.registerCustomEditor(java.sql.Timestamp.class, new PropertyEditorSupport() {

	            final SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

	            @Override
	            public void setAsText(String text) throws IllegalArgumentException {
	            	if ((null==text) || (text.trim().length()==0)){
	            		setValue(null);
	            		return;
	            	}
	                try {
	                    java.util.Date date = sf.parse(text);
	                    setValue(new Timestamp(date.getTime()));
	                } catch (ParseException e) {
	                    throw new IllegalArgumentException(e);
	                }
	            }
	        });
	        
	    }

	
}
